#include "context.h"

#include "state.h"

namespace HsmState {
Context::Context() {}

Context::~Context() {
    for (auto iter : _states) {
        if (iter.second._state) {
            delete iter.second._state;
            iter.second._state = nullptr;
        }
    }
    _states.clear();
}

// 开始状态机
bool Context::start(std::string name) {
    std::unordered_map<std::string, NodeState>::iterator iterMap =
        _states.find(name);
    if (iterMap != _states.end()) {
        _curNodeState = iterMap->second;
        _curName = iterMap->first;
        iterMap->second._state->start();
    }
    return false;
}

// 创建一个状态
// [in] state 状态对象，在Context销毁时，内部释放state
// [in] name  状态名称，为空名称为typedname的值
// [in] father_name 父状态的名称
// [out] 返回state
State* Context::createState(State* state,
                            std::string name,
                            std::string father_name) {
    NodeState node_state;
    node_state._state = state;
    node_state._state->setContext(this);
    node_state._father_name = father_name;
    _states[name] = node_state;
    return state;
}

// 更新当前状态
void Context::Update() { _curNodeState._state->update(); }

// 同步事件
// 发送一个事件，提供给root状态和当前状态处理
// 如果当前状态是子状态，则还会给父状态处理
void Context::SendEvent(EventData event_data) {
    RecursiveSend(_curNodeState, event_data);
}

// 异步事件
void Context::SendAsyncEvent(EventData event_data) {
    // todo 待实现
}

std::string Context::GetCurStateName() { return _curName; }

// 递归send
void Context::RecursiveSend(NodeState& node_state, EventData& event_data) {
    EventDeal eventDeal = node_state._state->runEventFunc(event_data);
    if (eventDeal == keepOn && !node_state._father_name.empty()) {
        std::unordered_map<std::string, NodeState>::iterator iterMap =
            _states.find(node_state._father_name);
        if (iterMap != _states.end()) {
            RecursiveSend(iterMap->second, event_data);
        }
    }
}

void Context::transForState(std::string name) {
    std::string str_name = std::string(name);
    std::unordered_map<std::string, NodeState>::iterator iterMap =
        _states.find(str_name);
    if (iterMap != _states.end()) {
        // 停止上一个状态
        _curNodeState._state->stop();

        // 初始化下一个状态
        _curNodeState = iterMap->second;
        _curName = iterMap->first;
        _curNodeState._state->start();
    }
}
}  // namespace HsmState